const vscode = require('vscode');
const hoverInfo = require('./hover/hover.json');
const outlineInfo = require('./hover/qftouch.json');
const fcunsInfo = require('./functions/fcuns.json');
const constInfo = require('./functions/constant.json');
const paramhoverInfo = require('./hover/paramhover.json');
const quickInfo = require('./hover/quick.json');
const colorInfo = require('./hover/color.json');
const fs = require("fs");
const path = require('path');
const https = require('https');
const iconv = require('iconv-lite');
const child_process = require('child_process');
const ffi = require('@lwahonen/ffi-napi');
const ref = require('@lwahonen/ref-napi');
const workPath = vscode.workspace.workspaceFolders[0].uri.path.match(/.+\/mirserver[^\/]*/i).toString().replace(/\//, '');

let voidPointerType = ref.refType(ref.types.void);
let cStringPointerType = ref.refType(ref.types.CString);
let user32 = ffi.Library('user32.dll', {
    'EnumWindows': [
        'int',
        [
            voidPointerType,
            'int32'
        ]
    ],
    'GetClassNameA': [
        'int',
        [
            'int',
            'string',
            'int'
        ]
    ],
    'GetWindowTextA': [
        'long',
        [
            'long',
            cStringPointerType,
            'long'
        ]
    ],
    'GetWindowThreadProcessId': [
        'int',
        [
            'int',
            'pointer'
        ]
    ],
    'FindWindowA': [
        'int',
        [
            'string',
            'string'
        ]
    ],
    'PostMessageW': [
        'bool',
        [
            'long',
            'long',
            'long',
            'long'
        ]
    ],
    'SendMessageA': [
        'bool',
        [
            'long',
            'long',
            'long',
            cStringPointerType
        ]
    ],
    'GetMenu': [
        'int',
        ['int']
    ],
    'GetMenuItemCount': [
        'int',
        ['int']
    ],
    'GetMenuStringA': [
        'int',
        [
            'int',
            'int',
            cStringPointerType,
            'int',
            'int'
        ]
    ],
    'GetSubMenu': [
        'int',
        [
            'int',
            'int'
        ]
    ],
    'FindWindowExA': [
        'int',
        [
            'int',
            'int',
            'int',
            'int'
        ]
    ],
    'EnumChildWindows': [
        'int',
        [
            'int32',
            voidPointerType,
            'int32'
        ]
    ]
});
let kernel32 = ffi.Library('kernel32.dll', {
    'OpenProcess': [
        'int',
        [
            'int',
            'bool',
            'int'
        ]
    ],
    'CloseHandle': [
        'int',
        ['int']
    ]
});
let psapi = ffi.Library('psapi.dll', {
    'GetModuleFileNameExA': [
        'int',
        [
            'int',
            'int',
            'string',
            'int'
        ]
    ]
});
let getm2serverClass = ffi.Callback('int', [
    'int32',
    'int32'
], function (p1, p2) {
    let WindowText = GetWindowTextA(p1);
    let ClassName = GetClassNameA(p1);
    let WindowThreadPId = GetWindowThreadProcessId(p1);
    if (WindowThreadPId === m2serverPID && (ClassName === 'TFrmMain' || ClassName === 'TfrmMain')) {
        hwnd = p1;
    }
    if (WindowText.search(/m2|控制/gi) > -1 && ClassName === 'TfrmMain' || ClassName === 'WTWindow') {
        user32.EnumChildWindows(hwnd, getm2serverChildClass, 0);
    }
    return 1;
});
let getm2serverChildClass = ffi.Callback('int', [
    'int32',
    'int32'
], function (p1, p2) {
    let ClassName = GetClassNameA(p1);
    let WindowThreadPId = GetWindowThreadProcessId(p1);
    if (WindowThreadPId === m2serverPID && (ClassName === 'TFrmMain' || ClassName === 'TfrmMain')) {
        hwnd = p1;
    }
    return 1;
});
let getm2servermsg = ffi.Callback('int', [
    'int32',
    'int32'
], function (p1, p2) {
    let ClassName = GetClassNameA(p1);
    let classNameslist = [
        'TMemo',
        'TRichEdit',
        'TRichView',
        'TJvRichEdit'
    ];
    if (classNameslist.includes(ClassName)) {
        textControl = p1;
    }
    return 1;
});
function GetWindowTextA(p1) {
    let alloc = Buffer.alloc(255);
    user32.GetWindowTextA(p1, alloc, 255);
    let from = Buffer.from(iconv.decode(alloc, 'gbk'));
    let readCString = ref.readCString(from, 0);
    return readCString;
};
function GetClassNameA(p1) {
    let alloc = Buffer.alloc(255);
    user32.GetClassNameA(p1, alloc, 255);
    let from = Buffer.from(iconv.decode(alloc, 'gbk'));
    let readCString = ref.readCString(from, 0);
    return readCString;
};
function GetWindowThreadProcessId(p1) {
    let alloc = Buffer.alloc(8);
    user32.GetWindowThreadProcessId(p1, alloc);
    let readUint32LE = alloc.readUint32LE(0);
    return readUint32LE;
};

function GetMenuStringA(p1, p2) {
    let alloc = Buffer.alloc(120);
    user32.GetMenuStringA(p1, p2, alloc, 120, 0);
    let from = Buffer.from(iconv.decode(alloc, 'gbk'));
    let readCString = ref.readCString(from, 0);
    return readCString;
};

function SendMessageA(p1) {
    let alloc = Buffer.alloc(1048576);
    user32.SendMessageA(p1, 13, 1048576, alloc);
    let from = Buffer.from(iconv.decode(alloc, 'gbk'));
    let readCString = ref.readCString(from, 0);
    return readCString;
}

let menuList;
let m2serverPID;
let hwnd;
let textControl;

let vararr = JSON.parse('{"A":{"1":"A1"},"G":{"1":"G1"},"U":{"1":"U1"},"T":{"1":"T1"},"N":{"1":"N1"},"S":{"1":"S1"},"J":{"1":"J1"},"Z":{"1":"Z1"},"P":{"1":"P1"},"D":{"1":"D1"},"M":{"1":"M1"},"个人标识":{"1":"个人标识1"},"S自定义":{"自定义":"自定义"},"N自定义":{"自定义":"自定义"}}');
let boxs = [],
    arrSS = [],
    arrA = [],
    arrG = [],
    arrI = [],
    arrS = [],
    arrN = [],
    arrU = [],
    arrT = [],
    arrP = [],
    arrD = [],
    arrM = [],
    arrTIMER = [],
    arrDc = [],
    arrX = [],
    arrJ = [],
    arrZ = [],
    arrB = [];

let $fcunsUrl = 'https://gitee.com/ouwenqi/996-engine-script-plugin/raw/master/src/functions/fcuns.json';
let $constantUrl = 'https://gitee.com/ouwenqi/996-engine-script-plugin/raw/master/src/functions/constant.json';
let $hoverUrl = 'https://gitee.com/ouwenqi/996-engine-script-plugin/raw/master/src/hover/hover.json';
let $paramhoverUrl = 'https://gitee.com/ouwenqi/996-engine-script-plugin/raw/master/src/hover/paramhover.json';
let $qftouchUrl = 'https://gitee.com/ouwenqi/996-engine-script-plugin/raw/master/src/hover/qftouch.json';
let $996mirUrl = 'https://gitee.com/ouwenqi/996-engine-script-plugin/raw/master/snippets/996mir.json';
let $tmLanguageUrl = 'https://gitee.com/ouwenqi/996-engine-script-plugin/raw/master/syntaxes/996mir.tmLanguage.json';

function activate(sparms) {
    console.log('996mir插件启动!');
    vscode.window.showInformationMessage('996mir插件启动');
    vscode.commands.executeCommand('setContext', 'myExtension.isActive', true);
    if (vscode.workspace.getConfiguration().get('workbench.colorTheme') === 'Default Dark Modern') {
        vscode.workspace.getConfiguration().update('workbench.colorTheme', 'One Dark Pro', true);
    }
    vscode.commands.executeCommand('extension.996mir-config.variable');
    let engineshow = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
    engineshow.text = '当前引擎:996mir';
    let clonebar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
    clonebar.text = '同步命令';
    clonebar.tooltip = '点击将自动同步网络仓库命令，自定义内容请备份';
    clonebar.command = 'extension.996mir-config.clone';
    clonebar.show();
    if (vscode.workspace.getConfiguration().get('996mir-config.obtainM2')) {
        let consolelogshow = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
        consolelogshow.text = 'M2日志';
        consolelogshow.tooltip = '输出脚本报错内容';
        consolelogshow.command = 'extension.996mir-config.consolelog';
        engineshow.show();
        consolelogshow.show();
        m2serverPID = findm2serverPID();
        if (m2serverPID == undefined) {
            menuList = [];
            vscode.window.showInformationMessage('未找到M2Server.exe,重载功能不可用');
        } else {
            user32.EnumWindows(getm2serverClass, 0);
            menuList = getmenuList(hwnd);
            let windowtext = GetWindowTextA(hwnd) || '';
            vscode.window.showInformationMessage('读取到服务端:' + windowtext);
        };
    };

    function funcjson(url, path) {
        https.get(url, function (res) {
            let data = [];
            let datalength = 0;
            res.on('data', function (chunk) {
                data.push(chunk);
                datalength += chunk.length;
            });
            res.on('end', function () {
                let josnfile = Buffer.concat(data, datalength);
                fs.writeFileSync(path, josnfile.toString());
            });
        }).on('error', function (err) {
            console.error('获取文件内容失败:', err);
        });
    };

    function refresh() {
        funcjson($fcunsUrl, vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath.replace(/\\/ig, "/") + '/src/functions/fcuns.json',);
        funcjson($constantUrl, vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath.replace(/\\/ig, "/") + '/src/functions/constant.json',);
        funcjson($hoverUrl, vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath.replace(/\\/ig, "/") + '/src/hover/hover.json',);
        funcjson($paramhoverUrl, vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath.replace(/\\/ig, "/") + '/src/hover/paramhover.json',);
        funcjson($qftouchUrl, vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath.replace(/\\/ig, "/") + '/src/hover/qftouch.json',);
        funcjson($996mirUrl, vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath.replace(/\\/ig, "/") + '/snippets/996mir.json');
        funcjson($tmLanguageUrl, vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath.replace(/\\/ig, "/") + '/syntaxes/996mir.tmLanguage.json',);
        vscode.window.showInformationMessage('更新完成，请重启', '重新启动').then(e => {
            if (e === '重新启动') {
                vscode.commands.executeCommand('workbench.action.reloadWindow');
            }
        });
    };

    function compare(a, b) {
        a = a.replace(/\$/, '0');
        b = b.replace(/\$/, '0');
        a = a.match(/\d+/);
        b = b.match(/\d+/);
        return a - b;
    };

    function findm2serverPID() {
        const fPcommand = process.platform == 'win32' ? 'wmic process where name="m2server.exe" get processid,executablepath,name /format:csv' : 'ps aux';
        let result = child_process.execSync(fPcommand).toString();
        result = result.split('\r\r\n');
        for (let index = 2; index < result.length; index++) {
            let processInfo = result[index].trim().split(',');
            if (processInfo.length === 4) {
                if (processInfo[2].toLowerCase().search('m2server') != -1) {
                    let processID = processInfo[3];
                    let processName = getProcessName(processID);
                    if (processName.toLowerCase() === path.join(workPath, '/mir200/m2server.exe').toLowerCase()) {
                        return parseInt(processID);
                    }
                }
            }
        }
    };

    function getProcessName(processID) {
        const OPENPROCESS = kernel32.OpenProcess(1040, false, processID);
        let alloc = Buffer.alloc(255);
        psapi.GetModuleFileNameExA(OPENPROCESS, 0, alloc, 255);
        let readCString = ref.readCString(Buffer.from(iconv.decode(alloc, 'gbk')), 0);
        kernel32.CloseHandle(OPENPROCESS);
        return readCString;
    };

    function getmenuList(p1) {
        let getMenu = user32.GetMenu(p1);
        let numMenuItems = 0;
        if (getMenu) {
            let menuItemCount = user32.GetMenuItemCount(getMenu);
            numMenuItems += menuItemCount;
            for (let index = 0; index < menuItemCount; index++) {
                let submenu = user32.GetSubMenu(getMenu, index);
                if (submenu) {
                    let submenuItemCount = user32.GetMenuItemCount(submenu);
                    numMenuItems += submenuItemCount;
                    for (let subIndex = 0; subIndex < submenuItemCount; subIndex++) {
                        let subsubmenu = user32.GetSubMenu(submenu, subIndex);
                        if (subsubmenu) {
                            numMenuItems += user32.GetMenuItemCount(subsubmenu);
                        }
                    }
                }
            }
            let menuList = [];
            for (let index = 0; index < numMenuItems; index++) {
                let menuItemText = GetMenuStringA(getMenu, index);
                if (menuItemText === '') {
                    menuItemText = '-----------------------------------';
                }

                menuList.push(menuItemText);
            }
            return menuList;
        }
    };

    function executeMenuCommand(p1) {
        p1.forEach(element => {
            user32.PostMessageW(hwnd, 273, element, 0);
        });
    }
    if (vscode.workspace.getConfiguration().get('996mir-config.obtainM2')) {
        let createOutputChannel = vscode.window.createOutputChannel('M2日志');
        let consolelogFunction = vscode.commands.registerCommand('extension.996mir-config.consolelog', function () {
            if (!hwnd) {
                vscode.window.showInformationMessage('未启动M2Server.exe');
            } else {
                user32.EnumChildWindows(hwnd, getm2servermsg, 0);
                let m2servermsg = SendMessageA(textControl);
                createOutputChannel.clear();
                createOutputChannel.appendLine(m2servermsg);
                createOutputChannel.show();
                let timer = setInterval(() => {
                    let m2servermsgnew = SendMessageA(textControl);
                    if (m2servermsgnew != m2servermsg) {
                        m2servermsg = m2servermsgnew
                        createOutputChannel.clear();
                        createOutputChannel.appendLine(m2servermsgnew);
                    }
                }, 1000);
            }
        });
        sparms.subscriptions.push(consolelogFunction);
        let getserverFunction = vscode.commands.registerCommand('extension.996mir-config.getserver', function () {
            m2serverPID = findm2serverPID();
            if (m2serverPID == undefined) {
                menuList = [];
                m2menut.refresh();
                vscode.window.showInformationMessage('未找到M2Server.exe,重载功能不可用');
            } else {
                user32.EnumWindows(getm2serverClass, 0);
                menuList = getmenuList(hwnd);
                m2menut.refresh();
                let windowtext = GetWindowTextA(hwnd) || '';
                vscode.window.showInformationMessage('读取到服务端:' + windowtext);
            }
        });
        sparms.subscriptions.push(getserverFunction);
        let menuclickFunction = vscode.commands.registerCommand('extension.996mir-config.menuclick', function (e) {
            executeMenuCommand([e]);
        });
        sparms.subscriptions.push(menuclickFunction);
        let oneClickHeavyLoadFunction = vscode.commands.registerCommand('extension.996mir-config.oneClickHeavyLoad', function () {
            let addons = vscode.workspace.getConfiguration().get('996mir-config.addons')
            executeMenuCommand(addons);
        });
        sparms.subscriptions.push(oneClickHeavyLoadFunction);
    };
    let clone = vscode.commands.registerCommand('extension.996mir-config.clone', function () {//同步仓库
        refresh();
    });
    sparms.subscriptions.push(clone);
    let refreshFunction = vscode.commands.registerCommand('extension.996mir-config.variable', function () {//变量查询
        if (fs.existsSync(workPath + '/var.json')) {
            vararr = JSON.parse(fs.readFileSync(workPath + '/var.json').toString());
        } else {
            let str = '{"A":{"1":"A1"},"G":{"1":"G1"},"U":{"1":"U1"},"T":{"1":"T1"},"N":{"1":"N1"},"S":{"1":"S1"},"J":{"1":"J1"},"P":{"1":"P1"},"D":{"1":"D1"},"M":{"1":"M1"},"个人标识":{"1":"个人标识1"},"S自定义":{"自定义":"自定义"},"N自定义":{"自定义":"自定义"}}';
            fs.writeFileSync(workPath + '/var.json', str)
        };
        let filePath = path.resolve(workPath + '/mir200/envir/');
        let arra = [];
        let arrg = [];
        let arri = [];
        let arrtimer = [];
        let arrx = [];
        let arrdc = [];
        let arru = [];
        let arrt = [];
        let arrp = [];
        let arrd = [];
        let arrm = [];
        let arrj = [];
        let arrz = [];
        let arrb = [];
        let arrn = [];
        let arrs = [];
        arrA = [];
        arrG = [];
        arrI = [];
        arrS = [];
        arrN = [];
        arrU = [];
        arrT = [];
        arrP = [];
        arrD = [];
        arrM = [];
        arrJ = [];
        arrZ = [];
        arrB = [];
        arrTIMER = [];
        arrDc = [];
        arrX = [];
        arrSS = [];
        boxs = [];

        function getDirTree(inputPath, callback) {
            let files = fs.readdirSync(inputPath);
            for (let file of files) {
                let filePath = inputPath + '/' + file;
                let fileState = fs.statSync(filePath);
                if (fileState.isDirectory()) {
                    getDirTree(filePath)
                } else if (filePath.search(/(questdiary)|(market_def)|(mapquest)|(robot_def)|(monitems)/ig) != -1 && filePath.search(/\.txt$/) != -1) {
                    let data = fs.readFileSync(filePath, 'utf8').toString().toLocaleUpperCase();
                    arra = data.match(/(?<=[\s\(])a(0|[1-9][0-9]{0,2})\b/ig);
                    arrg = data.match(/(?<=[\s\(])g(0|[1-9][0-9]{0,2})\b/ig);
                    arri = data.match(/(?<=[\s\(])i(0|[1-9][0-9]{0,2})\b/ig);
                    arrtimer = data.match(/\@ontimer\d{1,3}/ig);
                    arrx = data.match(/ \[\d{1,3}\]/ig);
                    arrdc = data.match(/\@stdmodefunc\d{1,3}/ig);
                    arru = data.match(/(?<=[\s\(])u(25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]\d|[0-9])\b/ig);
                    arrt = data.match(/(?<=[\s\(])t(25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]\d|[0-9])\b/ig);
                    arrp = data.match(/(?<=[\s\(])p(25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]\d|[0-9])\b/ig);
                    arrd = data.match(/(?<=[\s\(])d(25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]\d|[0-9])\b/ig);
                    arrm = data.match(/(?<=[\s\(])m(25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]\d|[0-9])\b/ig);
                    arrj = data.match(/(?<=[\s\(])j(25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]\d|[0-9])\b/ig);
                    arrz = data.match(/(?<=[\s\(])z(25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]\d|[0-9])\b/ig);
                    arrb = data.match(/(?<=[\s\(])b(25[0-5]|2[0-4][0-9]|1\d{2}|[1-9]\d|[0-9])\b/ig);
                    arrn = data.match(/(?<=[\[\s\(])n(0|[1-9][0-9]{0,2})\b/ig);
                    arrs = data.match(/(?<=[\s\(])s(0|[1-9][0-9]{0,2})\b/ig);
                    let ccdata = fs.readFileSync(filePath);
                    let cdata = iconv.decode(ccdata, 'gb18030');
                    arrSS = cdata.match(/s\$[^\s\)]+/ig);
                    boxs = cdata.match(/n\$[^\s\)]+/ig);
                    if (arra != null) {
                        arrA = arrA.concat(arra);
                        arrA = Array.from(new Set(arrA)).sort(compare)
                    };
                    if (arrg != null) {
                        arrG = arrG.concat(arrg);
                        arrG = Array.from(new Set(arrG)).sort(compare)
                    };
                    if (arri != null) {
                        arrI = arrI.concat(arri);
                        arrI = Array.from(new Set(arrI)).sort(compare)
                    };
                    if (arrtimer != null) {
                        arrTIMER = arrTIMER.concat(arrtimer);
                        arrTIMER = Array.from(new Set(arrTIMER)).sort(compare)
                    };
                    if (arrx != null) {
                        arrX = arrX.concat(arrx);
                        arrX = Array.from(new Set(arrX)).sort(compare)
                    };
                    if (arrdc != null) {
                        arrDc = arrDc.concat(arrdc);
                        arrDc = Array.from(new Set(arrDc)).sort(compare)
                    };
                    if (arru != null) {
                        arrU = arrU.concat(arru);
                        arrU = Array.from(new Set(arrU)).sort(compare)
                    };
                    if (arrt != null) {
                        arrT = arrT.concat(arrt);
                        arrT = Array.from(new Set(arrT)).sort(compare)
                    };
                    if (arrp != null) {
                        arrP = arrP.concat(arrp);
                        arrP = Array.from(new Set(arrP)).sort(compare)
                    };
                    if (arrd != null) {
                        arrD = arrD.concat(arrd);
                        arrD = Array.from(new Set(arrD)).sort(compare)
                    };
                    if (arrm != null) {
                        arrM = arrM.concat(arrm);
                        arrM = Array.from(new Set(arrM)).sort(compare)
                    };
                    if (arrj != null) {
                        arrJ = arrJ.concat(arrj);
                        arrJ = Array.from(new Set(arrJ)).sort(compare)
                    };
                    if (arrz != null) {
                        arrZ = arrZ.concat(arrz);
                        arrZ = Array.from(new Set(arrZ)).sort(compare)
                    };
                    if (arrb != null) {
                        arrB = arrB.concat(arrb);
                        arrB = Array.from(new Set(arrB)).sort(compare)
                    };
                    if (arrn != null) {
                        arrN = arrN.concat(arrn);
                        arrN = Array.from(new Set(arrN)).sort(compare)
                    };
                    if (arrs != null) {
                        arrS = arrS.concat(arrs);
                        arrS = Array.from(new Set(arrS)).sort(compare)
                    };
                    if (arrSS != null) {
                        arrS = arrS.concat(arrSS);
                        arrS = Array.from(new Set(arrS))
                    };
                    if (boxs != null) {
                        arrN = arrN.concat(boxs);
                        arrN = Array.from(new Set(arrN))
                    };
                }
            }
            callback && callback.call();
        }
        getDirTree(filePath, function () {
            vscode.window.showInformationMessage('查询完成')
        });
        gglobal.refresh();
    });
    sparms.subscriptions.push(refreshFunction);
    let strtrans = vscode.commands.registerCommand('extension.996mir-config.str', function () {//快速变量
        let selection = vscode.window.activeTextEditor.selection;
        let activeDoc = vscode.window.activeTextEditor.document;
        let selectedTxt = "<$str(" + getSelectedText(activeDoc, selection) + ")>";
        const {
            activeTextEditor
        } = vscode.window;
        const {
            document
        } = activeTextEditor;
        const position = vscode.window.activeTextEditor.selection;
        const edit = new vscode.WorkspaceEdit();
        edit.replace(document.uri, position, selectedTxt);
        vscode.workspace.applyEdit(edit);

        function getSelectedText(doc, selection) {
            return doc.getText(new vscode.Range(selection.start, selection.end))
        }
    });
    sparms.subscriptions.push(strtrans);
    let quickcolor = vscode.commands.registerCommand("extension.996mir-config.quickcolor", function () {//快速颜色
        let data = fs.readFileSync(vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath + '\\quickColor.html');
        let panel = vscode.window.createWebviewPanel('adWebview', "快速颜色", vscode.ViewColumn.Beside, {
            enableScripts: true
        });
        panel.webview.html = data.toString();
        let color = '';
        panel.webview.onDidReceiveMessage(message => {
            color = message;
            panel.dispose();
        });
        panel.onDidDispose(e => {
            if (color) {
                setTimeout(quickcolorFun, 100, color);
                quickcolorFun(color)
            }
        });

        function quickcolorFun(colorNum) {
            let selection = vscode.window.activeTextEditor.selection;
            let activeDoc = vscode.window.activeTextEditor.document;
            let selectedTxt = getSelectedText(activeDoc, selection);
            if (selectedTxt.match(/\<.*COLOR=\d+\>/ig)) {
                selectedTxt = selectedTxt.replace(/=\d+/g, "=" + colorNum);
                const {
                    activeTextEditor
                } = vscode.window;
                const {
                    document
                } = activeTextEditor;
                const position = vscode.window.activeTextEditor.selection;
                const edit = new vscode.WorkspaceEdit();
                edit.replace(document.uri, position, selectedTxt);
                vscode.workspace.applyEdit(edit)
            } else {
                selectedTxt = colorNum;
                const {
                    activeTextEditor
                } = vscode.window;
                const {
                    document
                } = activeTextEditor;
                const position = vscode.window.activeTextEditor.selection;
                const edit = new vscode.WorkspaceEdit();
                edit.replace(document.uri, position, selectedTxt);
                vscode.workspace.applyEdit(edit)
            }

            function getSelectedText(doc, selection) {
                return doc.getText(new vscode.Range(selection.start, selection.end))
            }
        }
    });
    sparms.subscriptions.push(quickcolor);
    let mapguide = vscode.commands.registerCommand("extension.996mir-config.mapquickguide", function () {//地图参数
        vscode.window.showQuickPick(quickInfo, {
            canPickMany: true,
            placeHolder: '选择参数插入'
        }).then(function (selected) {
            if (selected) {
                const {
                    activeTextEditor
                } = vscode.window;
                const {
                    document
                } = activeTextEditor;
                const position = vscode.window.activeTextEditor.selection.active;
                const edit = new vscode.WorkspaceEdit();
                let insertWords = "";
                selected.forEach(e => {
                    return insertWords = insertWords + " " + e.label;
                });
                edit.insert(document.uri, position, insertWords);
                vscode.workspace.applyEdit(edit)
            }
        })
    });
    sparms.subscriptions.push(mapguide);
    let guideFunction = vscode.commands.registerCommand('extension.996mir-config.quickguide', function () {//常用文件快捷
        const options = {
            preview: false,
        };
        let filename = '';
        let filename0 = '';
        vscode.window.showQuickPick(['QF', 'QM', '地图配置', '小地图配置', '机器人', '护身道具配置', '麻痹道具配置', '复活道具配置'], {
            canPickMany: false,
            placeHolder: '选择文件'
        }).then(function (selected) {
            if (selected) {
                switch (selected) {
                    case '地图配置':
                        fs.readdirSync(workPath + '/Mir200/Envir/').forEach(e => {
                            if (e.match(/^mapinfo\.txt$/ig)) {
                                filename = e
                            }
                        });
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/" + filename), options);
                        break;
                    case '机器人':
                        fs.readdirSync(workPath + '/Mir200/Envir/Robot_def/').forEach(e => {
                            if (e.match(/^autorunrobot\.txt$/ig)) {
                                filename = e
                            }
                        });
                        fs.readdirSync(workPath + '/Mir200/Envir/Robot_def/').forEach(e => {
                            if (e.match(/^robotmanage\.txt$/ig)) {
                                filename0 = e
                            }
                        });
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/Robot_def/" + filename), options);
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/Robot_def/" + filename0), options);
                        break;
                    case 'QF':
                        fs.readdirSync(workPath + '/Mir200/Envir/Market_Def/').forEach(e => {
                            if (e.match(/^qfunction\-0\.txt$/ig)) {
                                filename = e
                            }
                        });
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/Market_Def/" + filename), options);
                        break;
                    case 'QM':
                        fs.readdirSync(workPath + '/Mir200/Envir/MapQuest_Def/').forEach(e => {
                            if (e.match(/^qmanage\.txt$/ig)) {
                                filename = e
                            }
                        });
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/MapQuest_Def/" + filename), options);
                        break;
                    case '小地图配置':
                        fs.readdirSync(workPath + '/Mir200/Envir/').forEach(e => {
                            if (e.match(/^minimap\.txt$/ig)) {
                                filename = e
                            }
                        });
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/" + filename), options);
                        break;
                    case '护身道具配置':
                        fs.readdirSync(workPath + '/Mir200/Envir/').forEach(e => {
                            if (e.match(/^MagicShieldItemList\.txt$/ig)) {
                                filename = e
                            }
                        });
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/" + filename), options);
                        break;
                    case '麻痹道具配置':
                        fs.readdirSync(workPath + '/Mir200/Envir/').forEach(e => {
                            if (e.match(/^ParalysisItemList\.txt$/ig)) {
                                filename = e
                            }
                        });
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/" + filename), options);
                        break;
                    case '复活道具配置':
                        fs.readdirSync(workPath + '/Mir200/Envir/').forEach(e => {
                            if (e.match(/^RevivalItemList\.txt$/ig)) {
                                filename = e
                            }
                        });
                        vscode.window.showTextDocument(vscode.Uri.file(workPath + "/Mir200/Envir/" + filename), options);
                        break;
                }
            }
        });
        return;
    });
    sparms.subscriptions.push(guideFunction);
    let refword = '';
    let vg = vscode.commands.registerCommand('extension.996mir-config.vg', function (e) {
        vscode.commands.executeCommand('cancelSelection');
        // refword = e.replace(/\[/, '\\[').replace(/\]/, '\\]');
        // if (refword.search('@') == 0) {
        //     refword = refword + '\\b'
        // }
        // if (refword.match(/[a-z]\d+/ig) && refword.search('@') == -1) {
        //     refword = '(?<=[\\[\\s\\(])' + refword + '\\b';
        // }
        // vscode.commands.executeCommand('editor.action.referenceSearch.trigger');
        vscode.commands.executeCommand('workbench.action.findInFiles', { matchWholeWord: true, query: e });
    });
    sparms.subscriptions.push(vg);
    let definFunction = vscode.languages.registerDefinitionProvider({//快速跳转
        scheme: '*',
        language: '996mir'
    }, {
        provideDefinition(document, position, token) {
            const lineDocument = document.lineAt(position).text;
            const defWordpos = document.getWordRangeAtPosition(position, /@.*?(?=\>)/);
            const gotoWordpos = document.getWordRangeAtPosition(position, /@.+\n*/);
            if (document.fileName.search(/(autorunrobot\.txt)/ig) != -1) {
                let word = lineDocument.match(/@.*/i).toString();
                return new Promise(function (resolve, reject) {
                    vscode.workspace.openTextDocument(workPath + "/Mir200/Envir/Robot_def/RobotManage.txt").then(doc => {
                        let document = doc.getText().toString().toLowerCase();
                        let position = doc.positionAt(document.indexOf(word + "]"));
                        resolve(new vscode.Location(vscode.Uri.file(workPath + "/Mir200/Envir/Robot_def/RobotManage.txt"), position))
                    })
                })
            }
            if (document.fileName.search(/(mongen\.txt)/ig) != -1) {
                let filename = lineDocument.split(/\s+/)[3];
                return new vscode.Location(vscode.Uri.file(workPath + "/mir200/envir/MonItems/" + filename + '.txt'), new vscode.Position(0, 0))
            }
            if (document.fileName.search(/(mapquest\.txt)/ig) != -1) {
                let word1 = lineDocument.match(/\S+/ig)[5].toLocaleLowerCase();
                return new vscode.Location(vscode.Uri.file(workPath + "/mir200/envir/mapquest_def/" + word1 + '.txt'), new vscode.Position(0, 0))
            }
            if (document.fileName.search(/merchant\.txt/ig) != -1) {
                let word1 = lineDocument.match(/\S+/ig)[0].toLocaleLowerCase();
                let word2 = lineDocument.match(/\S+/ig)[1].toLocaleLowerCase();
                return new vscode.Location(vscode.Uri.file(workPath + "/Mir200/Envir/market_def/" + word1 + '-' + word2 + '.txt'), new vscode.Position(0, 0))
            }
            if (gotoWordpos != undefined && lineDocument.search(/(goto|delaygoto)/i) == 0) {
                const gotoWord = document.getText(gotoWordpos);
                const index = document.getText().indexOf("[" + gotoWord + "]");
                return new vscode.Location(document.uri, document.positionAt(index))
            }
            if (defWordpos != undefined) {
                const defWord = document.getText(defWordpos).replace("@@", "@");
                const index = document.getText().indexOf("[" + defWord + "]");
                return new vscode.Location(document.uri, document.positionAt(index))
            }
            if (lineDocument.search(/#call/i) == 0) {
                const fileName = lineDocument.match(/\[(.*)\]/i);
                const fileNamefull = fileName[1].replace(/\\/g, '/');
                return new vscode.Location(vscode.Uri.file(workPath + "/Mir200/Envir/QuestDiary/" + fileNamefull), new vscode.Position(0, 0))
            }
            if (lineDocument.search(/(config|list|clearnamelist|deltextlist|checkstringlist|checknamelist|addtextlist|addtextlistex|addnamelist|getrandomlinetext)/i) >= 0) {
                const fileName = lineDocument.match(/\\.*?\.(txt|ini)/i);
                const fileNamefull = fileName[0].replace(/\\/g, '/');
                return new vscode.Location(vscode.Uri.file(workPath + "/Mir200/Envir/" + fileNamefull), new vscode.Position(0, 0))
            }
            if (lineDocument.search(/setsctimer/i) == 0) {
                let word = lineDocument.match(/\s\d+/i).toString().replace(/\s+/ig, 'OnTimer').toLowerCase();
                return new Promise(function (resolve, reject) {
                    vscode.workspace.openTextDocument(workPath + "/Mir200/Envir/MapQuest_Def/QManage.txt").then(doc => {
                        let document = doc.getText().toString().toLowerCase();
                        let position = doc.positionAt(document.indexOf("@" + word + "]"));
                        resolve(new vscode.Location(vscode.Uri.file(workPath + "/Mir200/Envir/MapQuest_Def/QManage.txt"), position))
                    })
                })
            }
        }
    });
    sparms.subscriptions.push(definFunction);
    let hoverFunction = vscode.languages.registerHoverProvider({//参数提示
        scheme: '*',
        language: '996mir'
    }, {
        provideHover(document, position, token) {
            const hoveredWord = document.getText(document.getWordRangeAtPosition(position)).toLocaleLowerCase();
            const lineDocument = document.lineAt(position).text;
            const pos = position.character;
            const paramWord = lineDocument.split(/\s+/);

            const paramNum = lineDocument.slice(0, pos).split(/\s+/).length - 1;
            if (document.fileName.search(/(mapinfo\.txt)/ig) != -1) {
                let description = '';
                quickInfo.forEach(e => {
                    if (e.label.match(/\w+/i).toString().toLocaleLowerCase() === hoveredWord) {
                        description = e.description
                    }
                });
                return new vscode.Hover(description)
            }

            if (document.fileName.search(/(mapevent)/ig) != -1) {
                const hoverArr = ['地图编号', 'X坐标', 'Y坐标', '范围', '触发标识', '触发条件', '触发几率', '事件类型'];
                return new vscode.Hover(hoverArr[paramNum] + ":" + "\t\n" + paramWord[paramNum])
            }
            if (document.fileName.search(/(mapquest\.txt)/ig) != -1) {
                const hoverArr = ['地图编号', '变量', '判断', '怪物名称', '条件', '文件名'];
                return new vscode.Hover(hoverArr[paramNum] + ":" + "\t\n" + paramWord[paramNum])
            }
            // if (hoveredWord.search(/(magselffunc|takeon|takeoff|usercmd)/i) == 0) {
            //     const hoverWordin = hoveredWord.match(/\D+/);
            //     return new vscode.Hover(outlineInfo[hoverWordin[0]].example)
            // }
            if (hoverInfo[hoveredWord] != undefined) {

                return new vscode.Hover(hoverInfo[hoveredWord].example)
            } else {

                if (paramNum == 0) {
                    return new vscode.Hover(paramhoverInfo[paramWord[0].toLocaleLowerCase()]['paramall'] + ":" + "\t\n" + paramWord[paramNum])
                } else {
                    return new vscode.Hover(paramhoverInfo[paramWord[0].toLocaleLowerCase()][paramNum] + ":" + "\t\n" + paramWord[paramNum])
                }

            }
        }
    });
    sparms.subscriptions.push(hoverFunction);
    let colorComFunction = vscode.languages.registerCompletionItemProvider({//颜色补全
        scheme: '*',
        language: '996mir'
    }, {
        provideCompletionItems(document, position, token, context) {
            if (document.lineAt(position).text.search(/color/ig) == -1) {
                return
            }
            let Arr = Object.keys(colorInfo);
            let CompletionItem = Arr.map(dep => {
                let item = new vscode.CompletionItem(dep, vscode.CompletionItemKind.Color);
                item.label = colorInfo[dep].color;
                item.documentation = colorInfo[dep].color;
                return item;
            });
            return CompletionItem
        }
    }, '=');
    sparms.subscriptions.push(colorComFunction);
    let sectionComFunction = vscode.languages.registerCompletionItemProvider({//call补全@
        scheme: '*',
        language: '996mir'
    }, {
        provideCompletionItems(document, position, token, context) {
            if (document.lineAt(position).text.search(/\@/) == -1) {
                return
            }
            if (document.lineAt(position).text.search(/call/ig) != -1) {
                const lineDocument = document.lineAt(position).text;
                const fileName = lineDocument.match(/\[(.*)\]/i);
                const fileNamefull = fileName[1].replace(/\\/g, '//');
                let data = fs.readFileSync(workPath + "//Mir200//Envir//QuestDiary//" + fileNamefull);
                let c = [];
                let com = iconv.decode(data, 'gb18030');
                c.push(new vscode.CompletionItem(com.toString().match(/\@[^\]]+/i).toString().replace(/\@/i, ""), vscode.CompletionItemKind.Interface));
                return c;
            }
            let Arr0 = Array.from(new Set(document.getText().match(/[^\@]\@[^\n\s\]\>]+/ig)));
            let CompletionItem0 = Arr0.map(dep => {
                const depp = dep.replace(/.*\@/, '');
                let item = new vscode.CompletionItem(depp, vscode.CompletionItemKind.Interface);
                item.detail = '已有字段';
                return item;
            });
            return CompletionItem0
        }
    }, '\@');
    sparms.subscriptions.push(sectionComFunction);
    let pathcompletionFunction = vscode.languages.registerCompletionItemProvider({//文件路径补全
        scheme: '*',
        language: '996mir'
    }, {
        provideCompletionItems(document, position, token, context) {
            if (document.lineAt(position).text.search(/(var|call|clearnamelist|deltextlist|checkstringlist|checknamelist|addtextlist|addtextlistex|addnamelist|getrandomlinetext)/) == -1) {
                completionFunction;
                return;
            };
            return new Promise(function (resolve, reject) {
                let pathAdd = '/';
                if (document.lineAt(position).text.search(/call/ig) != -1) {
                    pathAdd = '/QuestDiary' + document.lineAt(position).text.match(/\\.*?[^\s\]]*/ig).toString().replace(/\\/ig, '/');
                } else {
                    pathAdd = document.lineAt(position).text.match(/\\.*?[^\s\]]*/ig).toString().replace(/\\/ig, '/');
                };
                let path = workPath + '/Mir200/Envir' + pathAdd.toString();
                fs.readdir(path, function (err, files) {
                    if (err) {
                        throw err;
                    } else {
                        let fileArr = files.filter(filefliter);

                        function filefliter(filename) {
                            if (filename.match(/.+\.(txt)|(ini)/ig)) {
                                return filename
                            }
                        };
                        let foldArr = files.filter(foldfliter);

                        function foldfliter(filename) {
                            if (!filename.match(/.+\./)) {
                                return filename
                            }
                        };
                        let completionItems1 = fileArr.map(dep => {
                            let item = new vscode.CompletionItem(dep, vscode.CompletionItemKind.File);
                            return item;
                        });
                        let completionItems2 = foldArr.map(dep => {
                            let item = new vscode.CompletionItem(dep, vscode.CompletionItemKind.Folder);
                            return item;
                        });
                        let List1 = new vscode.CompletionList().items.concat(completionItems1).concat(completionItems2);
                        resolve(List1);
                    }
                });
            });
        }
    }, '\\');
    sparms.subscriptions.push(pathcompletionFunction);
    let completionFunction = vscode.languages.registerCompletionItemProvider({//方法名及变量补全
        scheme: '*',
        language: '996mir'
    }, {
        provideCompletionItems(document, position, token, context) {
            let Arr = Object.keys(fcunsInfo);
            let Arr1 = Array.from(new Set(document.getText().match(/[ns]\$[^\s\)]+/ig)));
            let Arr2 = Array.from(new Set(document.getText().match(/[pdmnsigautzbPDMNSIGAUTZB]\d{1,3}/ig)));
            let Arr3 = Arr1.concat(Arr2);
            let CompletionItem1 = Arr.map(dep => {
                let item = new vscode.CompletionItem(dep, vscode.CompletionItemKind.Function);
                item.detail = fcunsInfo[item.label].details;
                return item;
            });
            let CompletionItem2 = Arr3.map(dep => {
                let item = new vscode.CompletionItem(dep, vscode.CompletionItemKind.Text);
                item.detail = "已有变量";
                return item;
            });
            let List = new vscode.CompletionList().items.concat(CompletionItem1).concat(CompletionItem2);
            return List;
        }
    });
    sparms.subscriptions.push(completionFunction);
    let constcompletionFunction = vscode.languages.registerCompletionItemProvider({//常量补全
        scheme: '*',
        language: '996mir'
    }, {
        provideCompletionItems(document, position, token, context) {
            if (true) {
                let Arr = Object.keys(constInfo);
                let CompletionItem1 = Arr.map(dep => {
                    let item = new vscode.CompletionItem(dep, vscode.CompletionItemKind.Constant);
                    item.detail = constInfo[item.label].details;
                    item.insertText = dep + ">";
                    return item;
                });
                let List = new vscode.CompletionList().items.concat(CompletionItem1);
                return List;
            }
        }
    }, "\$");
    sparms.subscriptions.push(constcompletionFunction);
    let symbolFunction = vscode.languages.registerDocumentSymbolProvider({//大纲
        scheme: '*',
        language: '996mir'
    }, {
        provideDocumentSymbols(document, token) {
            if (true) {
                const result = [];
                const sectionRegex = /^\s*\[([^\]]+)\]/;
                let prevSecName = null;
                let prevSecRangeStart = null;
                let prevSecRan996mirnd = null;
                for (let line = 0; line < document.lineCount; line++) {
                    const {
                        text
                    } = document.lineAt(line);
                    const secMatched = text.match(sectionRegex);
                    if (secMatched) {
                        if (prevSecName != null) {
                            prevSecRan996mirnd = new vscode.Position(line, 0);
                            const secLoc = new vscode.Location(document.uri, new vscode.Range(prevSecRangeStart, prevSecRan996mirnd));
                            const prevSectionSymbol = new vscode.SymbolInformation(prevSecName, vscode.SymbolKind.Interface, '', secLoc);
                            result.push(prevSectionSymbol)
                        }
                        prevSecName = secMatched[1];
                        const word = prevSecName.match(/[^\@]\D*/).toString().toLowerCase();
                        if (Object.keys(outlineInfo).indexOf(word) != -1) {
                            prevSecName = prevSecName + "(" + outlineInfo[word].example.match(/[^*]+/) + ")";
                            prevSecRangeStart = new vscode.Position(line, 0);
                            continue;
                        } else {
                            prevSecRangeStart = new vscode.Position(line, 0);
                            continue;
                        }
                    }
                }
                if (prevSecName != null) {
                    prevSecRan996mirnd = new vscode.Position(document.lineCount - 1, 0);
                    const secLoc = new vscode.Location(document.uri, new vscode.Range(prevSecRangeStart, prevSecRan996mirnd));
                    const prevSectionSymbol = new vscode.SymbolInformation(prevSecName, vscode.SymbolKind.Interface, '', secLoc);
                    result.push(prevSectionSymbol)
                }
                return result
            }
        }
    });
    sparms.subscriptions.push(symbolFunction);
    let foldFunction = vscode.languages.registerFoldingRangeProvider({//折叠
        scheme: '*',
        language: '996mir'
    }, {
        provideFoldingRanges(document, foldingContext, token) {
            const result = [];
            const sectionRegex = /^\s*\[([^\]]+)\]/;
            const keyRegex = /.*/;
            let prevSecName = null;
            let prevSecLineStart = null;
            let prevSecLineEnd = null;
            let lastKeyLine = null;
            for (let line = 0; line < document.lineCount; line++) {
                const { text } = document.lineAt(line);
                const secMatched = text.match(sectionRegex);
                if (secMatched) {
                    if (prevSecName != null) {
                        prevSecLineEnd = lastKeyLine;
                        const prevSecFoldingRange = new vscode.FoldingRange(prevSecLineStart, prevSecLineEnd, vscode.FoldingRangeKind.Region);
                        result.push(prevSecFoldingRange);
                    }
                    prevSecName = secMatched[1];
                    prevSecLineStart = line;
                    continue;
                }
                const keyMatched = text.match(keyRegex);
                if ((prevSecName != null) && keyMatched) {
                    lastKeyLine = line;
                    continue;
                }
            }
            if (prevSecName != null) {
                prevSecLineEnd = document.lineCount - 1;
                const prevSecFoldingRange = new vscode.FoldingRange(prevSecLineStart, prevSecLineEnd, vscode.FoldingRangeKind.Region);
                result.push(prevSecFoldingRange);
            }
            return result;
        }
    });
    sparms.subscriptions.push(foldFunction);
    let paramFunction = vscode.languages.registerSignatureHelpProvider({//参数提示
        scheme: '*',
        language: '996mir'
    }, {
        provideSignatureHelp(document, position, token, context) {
            const lineDocument = document.lineAt(position).text;
            const count = lineDocument.replace(/\s+/ig, " ").split(" ").length - 1;
            let word = lineDocument.match(/\S+/)[0].toLocaleLowerCase();
            if (paramhoverInfo[word][count]) {
                let s = new vscode.SignatureInformation(paramhoverInfo[word].paramall);
                let p = new vscode.ParameterInformation(paramhoverInfo[word][count]);
                s.parameters = [p];
                let sign = new vscode.SignatureHelp();
                sign.signatures = [s];
                sign.activeParameter = 0;
                sign.activeSignature = 0;
                return sign;
            }
        }
    }, " ");
    sparms.subscriptions.push(paramFunction);

    //颜色具现
    let DecorationType = [];
    let reg = [];
    let allcolorrange = new Array();
    for (let i = 0; i < Object.keys(colorInfo).length; i++) {
        DecorationType.push(vscode.window.createTextEditorDecorationType({
            before: { contentText: '', width: '0.7em', height: '0.7em', backgroundColor: colorInfo[i].color, },
        }));
    };
    function regexArr() {
        allcolorrange = new Array();
        for (let k = 0; k < Object.keys(colorInfo).length; k++) {
            reg.push(new RegExp('(?<=color=)' + k + '[>}|]', 'ig'));
            allcolorrange[k] = new Array()
        };
        range()
    };
    regexArr();
    function range() {
        let text = vscode.window.activeTextEditor.document.getText();
        for (let j = 0; j < Object.keys(colorInfo).length; j++) {
            let match;
            while (match = reg[j].exec(text)) {
                const sp = vscode.window.activeTextEditor.document.positionAt(match.index);
                const ep = vscode.window.activeTextEditor.document.positionAt(match.index + match[0].length);
                let colorRan = new vscode.Range(sp, ep);
                allcolorrange[j].push(colorRan);
            }
        };
        update()
    };
    function update() {
        if (vscode.workspace.getConfiguration().get('996mir-config.decoration')) {
            for (let l = 0; l < Object.keys(colorInfo).length; l++) {
                vscode.window.activeTextEditor.setDecorations(DecorationType[l], allcolorrange[l])
            }
        }
    };
    vscode.workspace.onDidChangeTextDocument(e => {
        for (let l = 0; l < Object.keys(colorInfo).length; l++) {
            allcolorrange[l] = new Array();
        };
        range();
    });
    vscode.window.onDidChangeActiveTextEditor(e => {
        for (let l = 0; l < Object.keys(colorInfo).length; l++) {
            vscode.window.activeTextEditor.setDecorations(DecorationType[l], []);
            allcolorrange[l] = new Array();
        };
        range();
    });
    vscode.window.createTextEditorDecorationType({
        after: { margin: '0 0 0 0.5rem' }
    });

    class m2menu {//m2加载界面
        constructor(context) {
            this.context = context;
            this.changeEvent = new vscode.EventEmitter();
            this.onDidChangeTreeData = this.changeEvent.event;
        }
        refresh() {
            this.changeEvent.fire();
        }
        getChildren() {
            if (menuList.length > 0) {
                let treeItems = [];
                menuList.forEach((menu, index) => {
                    let treeItem = new vscode.TreeItem();
                    treeItem = {
                        'label': index + '-' + menu,
                        'collapsibleState': 0
                    };
                    treeItem.command = {
                        'command': 'extension.996mir-config.menuclick',
                        'title': '',
                        'arguments': [index]
                    };
                    treeItems.push(treeItem);
                });
                return treeItems;
            } else {
                return [new vscode.TreeItem('未读取到M2Server')];
            }
        }
        getTreeItem(element) {
            return element;
        }
    }
    let m2menut = new m2menu(sparms);
    vscode.window.registerTreeDataProvider('mirmenu', m2menut);

    class gglobalc {//变量占用界面
        constructor(context) {
            this.context = context;
            this._onDidChangeTreeData = new vscode.EventEmitter();
            this.onDidChangeTreeData = this._onDidChangeTreeData.event;
            this.autoRefresh = true;
            vscode.window.onDidChangeActiveTextEditor(() => this.onActiveEditorChanged());
            vscode.workspace.onDidChangeTextDocument(e => this.onDocumentChanged(e));
            this.onActiveEditorChanged();
        };
        getChildren(res) {
            if (res) {
                switch (res) {
                    case 'A':
                        return arrA;
                    case 'G':
                        return arrG;
                    case 'I':
                        return arrI;
                    case 'U':
                        return arrU;
                    case 'T':
                        return arrT;
                    case 'N':
                        return arrN;
                    case 'S':
                        return arrS;
                    case 'J':
                        return arrJ;
                    case 'Z':
                        return arrZ;
                    case 'B':
                        return arrB;
                    case 'P':
                        return arrP;
                    case 'D':
                        return arrD;
                    case 'M':
                        return arrM;
                    case '个人标识':
                        return arrX;
                    case '计时器':
                        return arrTIMER;
                    case '个人标识':
                        return arrX;
                    case '双击触发':
                        return arrDc;
                }
            } else {
                return ['A', 'G', 'I', 'U', 'T', 'N', 'S', 'J', 'Z', 'B', 'P', 'D', 'M', '计时器', '个人标识', '双击触发']
            };
        };
        getTreeItem(element) {
            let res = new vscode.TreeItem(element);
            if (!(element.length == 1 || element.match("个人标识") || element.match("计时器") || element.match("双击触发"))) {
                let hover = res.label;
                if (res.label.match(/[agutnsjpdm]\d+/ig)) {
                    let x = res.label.match(/\w/ig)[0].toLocaleUpperCase();
                    let y = res.label.match(/\d+/)[0];
                    hover = vararr[x][y];
                };
                res.iconPath = vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath + '/images/number.svg';
                res.tooltip = hover;
                res.command = {
                    command: 'extension.996mir-config.vg',
                    title: '',
                    arguments: [res.label]
                };
                return res
            } else {
                res.collapsibleState = 1;
                res.iconPath = vscode.extensions.getExtension('ouwenqi.996engine-script-plugin').extensionPath + '/images/list.svg';
                return res;
            }
        };
        refresh(element) {
            if (element) {
                this._onDidChangeTreeData.fire(element);
            } else {
                this._onDidChangeTreeData.fire();
            }
        };
        clearMenu() {
            this.text = '';
            this.tree = null;
            this._onDidChangeTreeData.fire();
        };
        onActiveEditorChanged() {
            this.refresh()
        };
        onDocumentChanged() {
            this.refresh()
        };
    };
    let gglobal = new gglobalc();
    vscode.window.registerTreeDataProvider('gglobalVar', gglobal);
}
exports.activate = activate;

function deactivate() {
    console.log('插件释放!')
}
module.exports = {
    activate,
    deactivate
}